<template>
  <child-page>
    <div class="components-form-demo-advanced-search">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="标题" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'title',
              {
                initialValue: initInfo.title,
                rules: [
                  { required: true, message: '请输入标题！' },
                  {
                    validator: $validate.validateLength,
                    max: 50,
                    min: 1
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item
          label="封面图"
          v-bind="formItemLayout"
          help="建议图片宽高为：332px*187px"
        >
          <div class="clearfix">
            <a-upload
              v-decorator="[
                'upload',
                {
                  initialValue: initInfo.upload,
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '请上传封面图' }]
                }
              ]"
              accept="image/*"
              listType="picture-card"
              name="file"
              :multiple="false"
              :showUploadList="false"
              :action="$api.upload"
              :data="postData"
              :beforeUpload="beforeUpload"
            >
              <img
                v-if="imageUrl"
                :src="$api.picPre + imageUrl"
                alt="avatar"
                style="width: 120px"
              />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传封面图</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="视频" v-bind="formItemLayout">
          <a-upload
            name="file"
            accept="video/*"
            :multiple="false"
            :action="$api.upload"
            :data="postData"
            :beforeUpload="beforeUploadM"
            v-decorator="[
              'uploadM',
              {
                initialValue: initInfo.uploadM,
                valuePropName: 'fileList',
                getValueFromEvent: normFileM,
                rules: [{ required: true, message: '请上传视频' }]
              }
            ]"
          >
            <a-button> <a-icon type="upload" /> 上传视频 </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="简介" v-bind="formItemLayout">
          <div class="edit_container">
            <a-textarea
              placeholder=""
              :rows="5"
              v-decorator="[
                'intro',
                {
                  initialValue: initInfo.intro,
                  rules: [
                    { required: true, message: '请输入视频简介！' },
                    {
                      validator: $validate.validateLength,
                      max: 200,
                      min: 1
                    }
                  ]
                }
              ]"
            />
          </div>
        </a-form-item>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'center' }">
            <a-button type="primary" html-type="submit">
              提交
            </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </child-page>
</template>

<script>
import childPage from "@/components/childPageContent/index";
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  components: {
    childPage
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      previewVisible: false,
      previewImage: "",
      content: "",
      str: "",
      postData: {
        token: ""
      },
      initInfo: {
        upload: [],
        uploadM: []
      },
      loading: false,
      imageUrl: ""
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = JSON.parse(JSON.stringify(values));
          if (values.upload) {
            obj.pic = values.upload[0].response.key;
          }
          if (values.uploadM) {
            obj.video = values.uploadM[0].response.key;
          }
          delete obj.upload;
          delete obj.uploadM;
          let api = null;
          if (this.$route.name === "movieEdit") {
            api = this.$api.editMovieList;
            obj.id = this.$route.params.id;
          } else {
            api = this.$api.addMovieList;
          }
          this.$ajax
            .post(api, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.$router.push({ name: "leadingEndMovie" });
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "cxxy/movie/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 332;
        let height = 187;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为332px*187px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    beforeUploadM(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "cxxy/movie/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    normFileM(e) {
      if (e.fileList.length > 1) {
        e.fileList.splice(0, 1);
      }
      return e && e.fileList;
    },
    handleReset() {
      this.form.resetFields();
    },
    getInfo() {
      this.$ajax
        .post(this.$api.detailMovieList, {
          id: this.$route.params.id
        })
        .then(res => {
          this.initInfo = res;
          this.initInfo.upload = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.pic,
              name: res.title,
              response: {
                key: res.pic
              }
            }
          ];
          this.imageUrl = res.pic;
          this.initInfo.uploadM = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.video,
              name: res.title,
              response: {
                key: res.video
              }
            }
          ];
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    if (this.$route.name === "movieEdit") {
      this.getInfo();
    }
  }
};
</script>

<style scoped></style>
